package com.code;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.Global.Global;
import com.example.R;
import com.object.obTongMatHang;

public class DetailTongMatHang extends Activity {
	private LinearLayout llDetailTongMatHang;
	private String strNhomChon = "";
	private String strKhoChon = "";
	private String maHang = "";
	ArrayList<Integer> date_actual;
	private String date;
	private final int REQUEST_DETAIL_TMH = 100;
	private static String day;
	private static String year;
	private TableRow rowFocus;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detailtongmathang);

		llDetailTongMatHang = (LinearLayout) findViewById(R.id.llDetailTMH);
		strNhomChon = super.getIntent().getExtras()
				.getString("strNhomChonDetail");
		strKhoChon = super.getIntent().getExtras()
				.getString("strKhoChonDetail");
		date_actual = super.getIntent().getExtras()
				.getIntegerArrayList("dateDetail");
		maHang = super.getIntent().getExtras().getString("maHangDetail");
		date = String.valueOf(date_actual.get(2))
				+ DetailCuocGoi.setMonth(date_actual.get(1))
				+ Global.formatDay(date_actual.get(0));
		this.setTitle("Chi tiết mặt hàng");
		day = date_actual.get(0).toString();
		year = date_actual.get(2).toString();

		loadDateForDetailCustomer(strKhoChon, date, date, strNhomChon, maHang);
	}

	public void loadDateForDetailCustomer(String strKho, String dateFrom,
			String dateTo, String category, String productID) {
		Float totalThanhTien = 0.0f;
		Integer totalsoLuongXuat = 0;
		StringBuffer sql = new StringBuffer(
				" SELECT Phieuxuat.[Supplier ID] as MaKH,case when(isnull(Phieuxuat.Tennguoimua,'0')='0')then Phieuxuat.Diachigiaohang else Phieuxuat.Tennguoimua END as KhachHang, ");
		sql.append(" SUM(vattuxuat.SL) as SL,SUM((vattuxuat.SL * vattuxuat.dongia) * (1 + ISNULL(vattuxuat.Thue, 0)))AS ThanhTien,Phieuxuat.Diachigiaohang as DiaChi ");
		sql.append(" ,Phieuxuat.Ngaygio as Ngaygio");
		sql.append(" FROM Phieuxuat INNER JOIN vattuxuat ");
		sql.append(" ON Phieuxuat.SoCt = vattuxuat.SoCT INNER JOIN  Products ");
		sql.append(" ON vattuxuat.[Product ID] = Products.[Product ID] ");
		if (!strKho.equals("")) {
			sql.append(" AND Phieuxuat.MSK COLLATE DATABASE_DEFAULT ");
			sql.append(" IN (SELECT value FROM dbo.fn_Split('" + strKho
					+ "',',')) ");
		}
		sql.append(" AND  Phieuxuat.Ngay <=  cast('" + dateTo + "' as date)");
		sql.append(" AND  Phieuxuat.Ngay >=  cast('" + dateFrom + "' as date)");
		if (!category.equals(""))
			sql.append(" AND Products.[Category ID] =  '" + category + "'");
		sql.append(" AND Products.[Product ID] = '" + productID + "'");
		sql.append(" GROUP BY CASE WHEN(ISNULL(Phieuxuat.Tennguoimua,'0')='0')THEN Phieuxuat.Diachigiaohang ELSE Phieuxuat.Tennguoimua END");
		sql.append(",Phieuxuat.[Supplier ID],Phieuxuat.Diachigiaohang ,Phieuxuat.Ngaygio");
		ResultSet rs = Global.excuteQuerySQLServer(sql.toString());
		final TableLayout table = new TableLayout(this);
		llDetailTongMatHang.addView(table);
		TableRow trHead = new TableRow(this);
		trHead.setWeightSum(5.0f);

		TextView tvKhachHang = new TextView(this);
		tvKhachHang.setText("Khách hàng");
		TK_TongMatHang.setLayoutForTextView(tvKhachHang, true, Gravity.CENTER,
				10, 3.0f);

		TextView tvSLXuat = new TextView(this);
		tvSLXuat.setText("SLX");
		TK_TongMatHang.setLayoutForTextView(tvSLXuat, true, Gravity.CENTER, 10,
				1.0f);

		TextView tvThanhTien = new TextView(this);
		tvThanhTien.setText("TT");
		TK_TongMatHang.setLayoutForTextView(tvThanhTien, true, Gravity.CENTER,
				10, 1.0f,true);

		trHead.addView(tvKhachHang);
		trHead.addView(tvSLXuat);
		trHead.addView(tvThanhTien);
		table.addView(trHead);
		try {
			while (rs.next()) {

				// set value for TongMatHang
				final obTongMatHang obTMH = new obTongMatHang();
				if (rs.getString("KhachHang") != null)
					obTMH.setTenKhachHang(rs.getString("KhachHang"));
				if (rs.getInt("SL") != 0)
					obTMH.setSoLuongXuat(String.valueOf(rs.getInt("SL")));
				else
					obTMH.setSoLuongXuat("0");
				if (rs.getString("ThanhTien") != null)
					obTMH.setThanhTien(rs.getString("ThanhTien"));
				else
					obTMH.setThanhTien("0.0f");
				if (rs.getString("MaKH") != null)
					obTMH.setMaKH(rs.getString("MaKH"));
				if(rs.getString("DiaChi") != null)
					obTMH.setDiaChi(rs.getString("DiaChi").toString());
				
				if(rs.getString("Ngaygio") != null)
					obTMH.setNgayPX(rs.getString("Ngaygio"));
				// add date in textview
				TableRow trHeads = new TableRow(this);
				trHeads.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						for (int i = 0; i < table.getChildCount(); i++) {
							table.getChildAt(i).setBackgroundColor(
									Color.TRANSPARENT);
						}
						v.setBackgroundColor(Color.YELLOW);
					}
				});
				trHeads.setOnLongClickListener(new OnLongClickListener() {

					public boolean onLongClick(View v) {
						ArrayList<String> detail = new ArrayList<String>();
						ArrayList<String> infoCustomer = getInfoCustomer(obTMH
								.getMaKH());
						ArrayList<String> thanhTien_SL = DSCuocGoi.getDetailCalByCustomer(obTMH.getMaKH(), date, year); 
						// du nocuoiky
						String dateInput = year
								+ DetailCuocGoi.setMonth(date_actual.get(1)) + day;
						Float duNo = 0.0f;
						duNo = Float.valueOf(DSCuocGoi.duNoCuoiKy(obTMH.getMaKH(),dateInput));
						detail.add(0, maHang);
						detail.add(1, obTMH.getSoLuongXuat());
						detail.add(2, obTMH.getThanhTien());
						detail.add(3, obTMH.getTenKhachHang());
						detail.add(4, obTMH.getMaKH());
						detail.add(5, obTMH.getDiaChi());
//						Timestamp dateBan = getDateBan();
						//ngay ban gan nhat						
						detail.add(6,DetailCuocGoi.getHourtDate(obTMH.getNgayPX()));					
						if (infoCustomer != null) {
							// phone or mobile
							detail.add(7,!infoCustomer.get(0).equals("") ? infoCustomer
											.get(0) : infoCustomer.get(1));

						} else {
							detail.add(7, "");
						}
						//du no
						detail.add(8, Global.formatDecimalDetail(duNo));
						//so luong ban
						detail.add(9, thanhTien_SL.get(0));						
						//tong tien ban 
						detail.add(10, thanhTien_SL.get(1));
						if(DSCuocGoi.getMaxDateShipmentCustomer(obTMH.getNgayPX(),obTMH.getMaKH()) != null)
							detail.add(11, DSCuocGoi.getMaxDateShipmentCustomer(obTMH.getNgayPX(),obTMH.getMaKH()).toString());
						else
							detail.add(11,"");						
						if (obTMH.getMaKH().equals("")
								|| obTMH.getMaKH() != null) {
					
							Intent i = new Intent(DetailTongMatHang.this,DetailCustomerForTMH.class);
							Bundle b = new Bundle();
							b.putStringArrayList("detailCustomer", detail);
							b.putIntegerArrayList("dateDetailTMH", date_actual);
							b.putString("strKhoDetailTMH", strKhoChon);
							b.putString("strNhomChonDetailTMH", strNhomChon);
							i.putExtras(b);
							startActivityForResult(i, REQUEST_DETAIL_TMH);
						}
				
						return false;
					}
				});
				trHeads.setWeightSum(5.0f);

				TextView tvMaHangs = new TextView(this);
				tvMaHangs.setText(obTMH.getTenKhachHang());
				TK_TongMatHang.setLayoutForTextView(tvMaHangs,false,
						Gravity.CENTER, 10, 3.0f);

				TextView tvSLXuats = new TextView(this);
				tvSLXuats.setText(obTMH.getSoLuongXuat());
				TK_TongMatHang.setLayoutForTextView(tvSLXuats, false,
						Gravity.CENTER, 10, 1.0f);

				TextView tvThanhTiens = new TextView(this);
				tvThanhTiens.setText(Global.formatDecimal(Float.valueOf(obTMH
						.getThanhTien())));
				TK_TongMatHang.setLayoutForTextView(tvThanhTiens,false,
						Gravity.RIGHT, 10, 1.0f,true);
//				tvThanhTiens.setGravity(Gravity.RIGHT);

				trHeads.addView(tvMaHangs);
				trHeads.addView(tvSLXuats);
				trHeads.addView(tvThanhTiens);
				table.addView(trHeads);

				totalsoLuongXuat = totalsoLuongXuat
						+ Integer.valueOf(obTMH.getSoLuongXuat());
				totalThanhTien = totalThanhTien
						+ Float.valueOf(Float.valueOf(obTMH.getThanhTien()));
			}

			// add date in textview
			TableRow trHeadEnd = new TableRow(this);
			trHeadEnd.setWeightSum(5.0f);

			TextView tvMaHangEnd = new TextView(this);
			tvMaHangEnd.setText("Tổng");
			TK_TongMatHang.setLayoutForTextView(tvMaHangEnd, false,
					Gravity.CENTER, 10, 3.0f);
			tvMaHangEnd.setBackgroundResource(R.layout.border_topleftbottom);

			TextView tvSLXuatEnd = new TextView(this);
			tvSLXuatEnd.setText(totalsoLuongXuat.toString());
			TK_TongMatHang.setLayoutForTextView(tvSLXuatEnd, false,
					Gravity.CENTER, 10, 1.0f);
			tvSLXuatEnd.setBackgroundResource(R.layout.border_topleftbottom);

			TextView tvThanhTienEnd = new TextView(this);
			tvThanhTienEnd.setText(Global.formatDecimal(totalThanhTien));
			TK_TongMatHang.setLayoutForTextView(tvThanhTienEnd, false,
					Gravity.RIGHT, 10, 1.0f,true);
			tvThanhTienEnd.setBackgroundResource(R.layout.border);

			trHeadEnd.addView(tvMaHangEnd);
			trHeadEnd.addView(tvSLXuatEnd);
			trHeadEnd.addView(tvThanhTienEnd);
			table.addView(trHeadEnd);

			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// get info customer
	public ArrayList<String> getInfoCustomer(String supplierID) {
		ArrayList<String> customer = new ArrayList<String>();
		StringBuffer sql = new StringBuffer(
				" SELECT [Supplier ID] as MaKH,[Company Name],CASE when (Phone is null) then '' else Phone end as Phone" +
				",CASE when (DTDD is null) then '' else DTDD end as DTDD from Suppliers where  [Supplier ID] = '"
						+ supplierID + "'");
		ResultSet rs = Global.excuteQuerySQLServer(sql.toString());
		try {
			if (rs.next()) {
				// customer.add(0, rs.getString(1));
				customer.add(0,rs.getString(3));
				customer.add(1, rs.getString(4));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return customer;
	}
	
	public static Timestamp getDateBan(String day,String month,String year,String supplierID) {
		Timestamp t= null;
		StringBuffer sql = new StringBuffer(
				" SELECT  Ngay ");
		sql.append(" FROM CuocGoi ");
		sql.append(" WHERE DATEPART(DD, Ngay) = '" + day + "'");
		sql.append(" AND DATEPART(MM, Ngay) = '" + month + "'");
		sql.append(" AND DATEPART(YY, Ngay) = '" + year + "'");		
		sql.append(" AND ISNULL(SoPhieu,'') !='' ");	
		sql.append(" AND [Supplier ID] = '"+supplierID+"'" );
		sql.append(" ORDER BY Ngay DESC ");
		ResultSet rs = Global.excuteQuerySQLServer(sql.toString());
		try {
			if(rs.next())			
				t = rs.getTimestamp(1);			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return t;		
	}
}
